/// 生成版面布局
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Text;

namespace ReaWTM.LayuiHelper
{
	public abstract class BaseElementTag : BaseTag
	{
		private string id;

		public int? Colspan { get; set; }

		public string Id
		{
			get
			{
				if (string.IsNullOrEmpty(id))
				{
					id = $"{this.GetType().Name.Replace("TagHelper", "")}{Guid.NewGuid():N}";
				}
				return id;
			}
			set { id = value; }
		}

		public int? Height { get; set; }

		public int? Width { get; set; }

		public string Class { get; set; }

		public string Style { get; set; }


		private string GetXlCol(TagHelperContext context, int col)
		{
			if (context.Items.ContainsKey("wt-print"))
			{
				return $"layui-col-xs{col}";
			}
			if (context.Items.ContainsKey("iprm"))
			{
				int iprm = (int)context.Items["iprm"];
				if (iprm != 1)
				{
					return $"layui-col-xs{12 / iprm}";
				}
			}
			return "";
		}
		void SetStyle(TagHelperOutput output)
		{
			StringBuilder builder = new StringBuilder(Style);

			if (Width.HasValue)
			{
				builder.Append($"width:{Width}px;");
			}
			if (Height.HasValue)
			{
				builder.Append($"min-height:{Height}px;");
			}
			if (string.IsNullOrEmpty(Style) == false)
			{
				if (this is TreeTagHelper)
				{
					builder.Append("overflow-y:auto;overflow-x:hidden;");
				}
				TagHelperAttribute prestyle = null;
				if (output.Attributes.TryGetAttribute("style", out prestyle))
				{
					string s = prestyle.Value.ToString();
					if (s.EndsWith(";") == false)
					{
						s += ";";
					}
					builder.Append(s);
				}

				output.Attributes.SetAttribute("style", builder.ToString());
			}
		}
		public override void Process(TagHelperContext context, TagHelperOutput output)
		{


			if (WtSize != WtSizeEnum.None)
			{
				output.Attributes.Add("wtsize", base.GetWtSize());
			}

			if (output.Attributes.ContainsName("id") == false && string.IsNullOrEmpty(Id) == false)
			{
				output.Attributes.SetAttribute("id", Id);
			}

			if (string.IsNullOrEmpty(Class) == false)
			{
				output.Attributes.SetAttribute("class", Class);
			}

			SetStyle(output);

			var html_sb = new StringBuilder();

			if (context.Items.ContainsKey("ipr"))
			{
				int? ipr = (int?)context.Items["ipr"];
				if (ipr > 0)
				{
					int col = 12 / ipr.Value;
					if (Colspan != null)
					{
						col *= Colspan.Value;
					}

					string xs_class = GetXlCol(context, col);

					html_sb.Append($"<div class='layui-col-md{col} layui-col-sm{col} {xs_class}'>");
					html_sb.Append(output.PreElement.GetContent());

					output.PreElement.SetHtmlContent(html_sb.ToString());
					output.PostElement.AppendHtml("</div>");
				}
				if (this is CardTagHelper || this is FormTagHelper || this is ContainerTagHelper || this is TreeContainerTagHelper || this is SearchPanelTagHelper)
				{
					context.Items.Remove("ipr");
				}
			}

		}
	}
}